#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <pthread.h>

//number of iterations
#define N 100000
#define NTHREADS 4

//generates an random (x,y) point then verify if its inside the circle
void *verifica(void*);

//threads constant
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

//global counter for points inside the circle
int counter;

int main()
{
    int i,j;

    pthread_t thread_id[NTHREADS];

    srand(time(NULL));
    counter = 0;

    //generates the threads
    for(i=0; i < NTHREADS; i++)
    {
        pthread_create( &thread_id[i], NULL, verifica, NULL );
    }

    //wait for threads ending
    for(j=0; j < NTHREADS; j++)
    {
        pthread_join( thread_id[j], NULL);
    }

    //print pi estimate
    printf("%lf\n",4*(double)counter/(double)(NTHREADS * N));

    return 0;
}

void *verifica(void *ptr)
{

    int i;
    double x, y;

    for(i = 0; i < N; i++)
    {
        //generate an random (x,y) point
        x = (double)rand() / (double)RAND_MAX;
        y = (double)rand() / (double)RAND_MAX;

        //verify if (x,y) is inside the circle
        if(x*x+y*y <= 1)
            counter++;


        printf("%lf\n",4*(double)counter/(double)(NTHREADS * N));
    }
}
